#include "stm32f10x.h"                  // Device header

void PWM_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA ,ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Pin  = GPIO_Pin_11;
	GPIO_InitStructure.GPIO_Speed  = GPIO_Speed_50MHz ;
	GPIO_Init(GPIOA,&GPIO_InitStructure);
	
	TIM_InternalClockConfig(TIM1);
	
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_Period = 200-1;  //ARR
	TIM_TimeBaseInitStructure.TIM_Prescaler = 7200 - 1; //PSC
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM1,&TIM_TimeBaseInitStructure);
	
	TIM_OCInitTypeDef TIM_OC4InitStructure;
	TIM_OCStructInit(&TIM_OC4InitStructure);
	TIM_OC4InitStructure.TIM_OCMode = TIM_OCMode_PWM1;
	TIM_OC4InitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM_OC4InitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OC4InitStructure.TIM_Pulse = 10; //CCR
	TIM_OC4Init(TIM1,&TIM_OC4InitStructure);
	
	TIM_ARRPreloadConfig(TIM1, ENABLE);  //使能预装载寄存器(神来之笔！！
	TIM_Cmd(TIM1,ENABLE);
	TIM_CtrlPWMOutputs(TIM1, ENABLE);    //pwm输出
	
}

void PWM_SetCompare(uint16_t Compare)
{
	TIM_SetCompare4(TIM1,Compare);
}

void Servo_SetAngle(uint8_t _angle)
{
	float pwm_out = _angle*0.11f+5;//(25-5)/180=0.11
	PWM_SetCompare(pwm_out);
}
